package xin.ryven.car.android.network

import android.content.Context
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import xin.ryven.car.android.api.ApiService
import xin.ryven.car.android.api.AuthApi
import java.util.concurrent.TimeUnit

object NetworkConfig {

    // 根据设备类型自动选择合适的BASE_URL
    private fun getBaseUrl(): String {
        // return "http://192.168.1.7:8666/"
        return "https://ryven.xin/tools/"
    }

    fun createOkHttpClient(context: Context, authApi: AuthApi): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(AuthInterceptor(context, authApi))
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
    }

    // 创建不需要认证的OkHttpClient (用于某些公开API)
    fun createSimpleOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
    }

    fun createRetrofit(context: Context): Retrofit {
        // 先创建一个临时的AuthApi实例
        val tempRetrofit = Retrofit.Builder()
            .baseUrl(getBaseUrl())
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val authApi = tempRetrofit.create(AuthApi::class.java)
        val okHttpClient = createOkHttpClient(context, authApi)

        return Retrofit.Builder()
            .baseUrl(getBaseUrl())
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    // 创建简单的Retrofit实例 (不需要认证拦截器)
    fun createSimpleRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(getBaseUrl())
            .client(createSimpleOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getAuthApi(context: Context): AuthApi {
        return createRetrofit(context).create(AuthApi::class.java)
    }

    // 获取带认证的ApiService
    fun getApiService(context: Context): ApiService {
        return createRetrofit(context).create(ApiService::class.java)
    }

    // 获取不需要认证的ApiService
    fun getSimpleApiService(): ApiService {
        return createSimpleRetrofit().create(ApiService::class.java)
    }
} 